package com.yuan.leetcode.JianZhiOffer;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by yuanhaowu
 * Time 2022/6/18 10:58
 * <p>
 * 给你二叉树的根节点 root 和一个整数目标和 targetSum ，找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
 * <p>
 * 输入：root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
 * 输出：[[5,4,11,2],[5,8,4,5]]
 */
public class offer34 {
    LinkedList<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> pathSum(TreeNode root, int target) {
        dfs(root, target);
        return res;
    }

    private void dfs(TreeNode node, int target){
        if(node == null){
            return;
        }
        path.add(node.val);
        target = target - node.val;
        if(target == 0 && node.left == null && node.right == null){
            res.add(new LinkedList<>(path));
        }
        dfs(node.left, target);
        dfs(node.right, target);
        path.removeLast();
    }
}
